import pymysql
from pymysql.cursors import DictCursor
from contextlib import contextmanager

class MySQLUtil:
    def __init__(self):
        self.host = "101.237.129.10"
        self.port = 3306
        self.user = "root"
        self.password = "Wing1Q2W#E"
        self.database = "bishushanzhuang"
        self.charset = "utf8mb4"

    @contextmanager
    def get_connection(self):
        """获取数据库连接"""
        conn = pymysql.connect(
            host=self.host,
            port=self.port,
            user=self.user,
            password=self.password,
            database=self.database,
            charset=self.charset,
            cursorclass=DictCursor
        )
        try:
            yield conn
        finally:
            conn.close()

    def execute_query(self, sql, params=None):
        """执行查询操作"""
        with self.get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute(sql, params or ())
                return cursor.fetchall()

    def execute_update(self, sql, params=None):
        """执行更新操作"""
        with self.get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute(sql, params or ())
                conn.commit()
                return cursor.rowcount

    def execute_many(self, sql, params_list):
        """批量执行操作"""
        with self.get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.executemany(sql, params_list)
                conn.commit()
                return cursor.rowcount

    def get_one(self, sql, params=None):
        """获取单条记录"""
        with self.get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute(sql, params or ())
                return cursor.fetchone()

    def get_all(self, sql, params=None):
        """获取所有记录"""
        with self.get_connection() as conn:
            with conn.cursor() as cursor:
                cursor.execute(sql, params or ())
                return cursor.fetchall() 